<?php

/**
 * Description of G_Redis
 *
 * @author Monk <eoe2005@gmail.com>
 */
if (class_exists('Redis') === false)
{
    trigger_error('系统不支持Redis模块');
    die();
}
class G_Redis extends GC_Cache
{
    public $_redis;
    public function __construct($server,$db = 1)
    {
        $this->_redis = new Redis;
        if(is_array($server)){
            $len = count($server);
            if($len == 1){
                $this->_redis->connect($server['host']);
            }elseif($len >= 2){
                $this->_redis->connect($server['host'],$server['port']);
            }
        }else{
            $this->_redis->connect($server);
        }
        $this->_redis->select($db);
    }

    public function dec($key, $step = 1)
    {
        return $this->_redis->decrBy($key,$step);
    }

    public function delete($keys)
    {
        return $this->_redis->delete($keys);
    }

    public function exists($keys)
    {
        if(is_array($keys)){
            $rs = array();
            foreach ($keys AS $k){
                if($this->_redis->exists($k)){
                    $rs[] = $k;
                }
            }
            return $rs;
        }
        return $this->_redis->exists($keys);
    }

    public function flushAll()
    {
        return $this->_redis->flushDB();
    }

    public function get($key)
    {
        $rs = $this->_redis->get($key);
        if($rs){
            $rs = unserialize($rs);
        }
        return $rs;
    }

    public function inc($key, $step = 1)
    {
        return $this->_redis->incrBy($key,$step);
    }

    public function set($key, $val, $timeout = 0)
    {
        return $this->_redis->setex($key,$timeout,  serialize($val));
    }

}
